package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.mapper.CoursePublishPreMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/21 18:47
 */
@Service
@Slf4j
public class CoursePublishServiceImpl implements CoursePublishService {
    
    @Resource
    CourseBaseInfoService courseBaseInfoService;
    
    @Resource
    TeachplanService teachplanService;
    
    @Resource
    CourseMarketMapper courseMarketMapper;
    
    @Resource
    CoursePublishPreMapper coursePublishPreMapper;
    
    @Resource
    CourseBaseMapper courseBaseMapper;
    
    @Resource
    CoursePublishMapper coursePublishMapper;
    
    @Resource
    MqMessageService mqMessageService;
    
    @Resource
    MediaServiceClient mediaServiceClient;
    
    @Resource
    RedisTemplate redisTemplate;
    
    @Resource
    RedissonClient redissonClient;
    
    
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        // 课程基本信息,营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        coursePreviewDto.setCourseBase(courseBaseInfo);
        // 课程计划信息
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        coursePreviewDto.setTeachplans(teachplanTree);
        return coursePreviewDto;
    }

    @Transactional
    @Override
    public void commitAudit(Long companyId, Long courseId) {

        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        if (courseBaseInfo == null){
            XueChengPlusException.cast("课程找不到");
        }

        // 审核状态
        String auditStatus = courseBaseInfo.getAuditStatus();

        // 如果课程的审核状态为已提交则不允许提交
        if (auditStatus.equals("202003")){
            XueChengPlusException.cast("课程已提交请等待审核");
        }
        
        // 本机构只能提交本机构的课程
        
        // 课程的图片、计划信息没有填写也不允许提交
        String pic = courseBaseInfo.getPic();
        if (StringUtils.isEmpty(pic)){
            XueChengPlusException.cast("请求上传图片");
        }

        // 查询课程计划
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        if (teachplanTree == null || teachplanTree.size() < 1){
            XueChengPlusException.cast("请编写课程计划");
        }

        // 查询到课程基本信息、营销信息、计划等信息插入到课程预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfo, coursePublishPre);
        // 设置机构id
        coursePublishPre.setCompanyId(companyId);
        // 营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        // 转json
        String courseMarketJson = JSON.toJSONString(courseMarket);
        coursePublishPre.setMarket(courseMarketJson);
        // 计划信息转json
        String teachplanJson = JSON.toJSONString(teachplanTree);
        coursePublishPre.setTeachplan(teachplanJson);
        // 状态为已提交
        coursePublishPre.setStatus("202003");
        coursePublishPre.setCreateDate(LocalDateTime.now());
        
        // 查询预发布表，如果有记录则更新，没有则插入
        CoursePublishPre coursePublishPreObj = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreObj == null){
            // 插入
            coursePublishPreMapper.insert(coursePublishPre);
        }else {
            // 更新
            coursePublishPreMapper.updateById(coursePublishPre);
        }

        // 更新课程基本信息表的审核状态为已提交
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        // 审核状态为已提交
        courseBase.setAuditStatus("202003");
        
        courseBaseMapper.updateById(courseBase);

    }

    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {


        // 查询预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPre == null){
            XueChengPlusException.cast("课程没有审核记录不允许发布");
        }

        // 状态
        String status = coursePublishPre.getStatus();
        // 课程如果没有审核通过不允许发布
        if (!status.equals("202004")) {
            XueChengPlusException.cast("课程没有审核通过不允许发布");
        }
        
        
        // 向课程发布表写入数据
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        // 先查询课程发布，如果有则更新，没有再添加
        CoursePublish coursePublishObj = coursePublishMapper.selectById(courseId);
        if (coursePublishObj == null){
            coursePublishMapper.insert(coursePublish);
        }else {
            coursePublishMapper.updateById(coursePublish);
        }

        // 向消息表写入数据
        saveCoursePublishMessage(courseId);

        // 将预发布表数据删除
        coursePublishPreMapper.deleteById(courseId);
    }

    @Override
    public File generateCourseHtml(Long courseId) {
        //静态化文件
        File htmlFile  = null;

        try {
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);

            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//            System.out.println(content);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("coursepublish",".html");
            log.debug("课程静态化，生成静态文件:{}",htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("课程静态化异常:{}",e.toString());
            XueChengPlusException.cast("课程静态化异常");
        }

        return htmlFile;
    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        try {
            MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
            String upload = mediaServiceClient.upload(multipartFile, "course/" + courseId + ".html");
            if (upload == null){
                log.debug("远程调用Media上传到Minio的结果为null,课程id:{}", courseId);
                XueChengPlusException.cast("上传静态文件过程中存在异常");
            }
        } catch (IOException e) {
            e.printStackTrace();
            XueChengPlusException.cast("上传静态文件过程中存在异常");
        }
    }

    /**
     * @description 保存消息表记录
     * @param courseId  课程id
     * @return void
     */
    private void saveCoursePublishMessage(Long courseId){
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", courseId + "", null, null);
        
        if (mqMessage == null){
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }
        

    }

    /**
     * 根据课程id 查询课程发布信息
     * @param courseId 课程id
     * @return
     */
    public CoursePublish getCoursePublish(Long courseId){
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish ;
    }
    
    // 解决缓存穿透
    /*@Override
    public CoursePublish getCoursePublishCache(Long courseId) {

        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
        // 防止缓存穿透
        if ("".equals(jsonObj.toString())){
            return null;
        }
        if (jsonObj != null){
            // 缓存中有直接返回数据
            String jsonString = jsonObj.toString();
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        }
        // 从数据库查询
        CoursePublish coursePublish = getCoursePublish(courseId);
        if (coursePublish != null){
            // 查询完成在存储到redis
            redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish));
            return coursePublish;
        }
        // 数据库中没有数据 防止缓存穿透
        redisTemplate.opsForValue().set("course:" + courseId, "", 30, TimeUnit.SECONDS);
        return null;
    }*/

    // 解决缓存击穿
    /*@Override
    public CoursePublish getCoursePublishCache(Long courseId) {
        
        
        
        
        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
        // 防止缓存穿透
        if ("".equals(jsonObj.toString())){
            return null;
        }
        if (jsonObj != null){
            // 缓存中有直接返回数据
            String jsonString = jsonObj.toString();
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        }
        // 双重检查锁
        synchronized (this){

            Object jsonObj2 = redisTemplate.opsForValue().get("course:" + courseId);
            if (jsonObj2 != null){
                // 第二次检查，如果有就直接返回数据，防止重复查询数据库
                String jsonString2 = jsonObj2.toString();
                CoursePublish coursePublish2 = JSON.parseObject(jsonString2, CoursePublish.class);
                return coursePublish2;
            }
            // 从数据库查询
            CoursePublish coursePublish = getCoursePublish(courseId);
            if (coursePublish != null){
                // 查询完成在存储到redis
                redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish));
                return coursePublish;
            }
            // 数据库中没有数据 防止缓存穿透
            redisTemplate.opsForValue().set("course:" + courseId, "", 30, TimeUnit.SECONDS);
        }
        
        return null;
    }*/

    // setNX 解决分布式锁问题
    /*@Override
    public CoursePublish getCoursePublishCache(Long courseId) {




        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
        // 防止缓存穿透
        if ("".equals(jsonObj.toString())){
            return null;
        }
        if (jsonObj != null){
            // 缓存中有直接返回数据
            String jsonString = jsonObj.toString();
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        }
        // 分布式锁，通过setnx实现
        String lockKey = "courseLock:" + courseId;
        try {
            Boolean lock01 = redisTemplate.opsForValue().setIfAbsent(lockKey, "01");
            if (lock01){
                Object jsonObj2 = redisTemplate.opsForValue().get("course:" + courseId);
                if (jsonObj2 != null){
                    // 第二次检查，如果有就直接返回数据，防止重复查询数据库
                    String jsonString2 = jsonObj2.toString();
                    CoursePublish coursePublish2 = JSON.parseObject(jsonString2, CoursePublish.class);
                    return coursePublish2;
                }
                // 从数据库查询
                CoursePublish coursePublish = getCoursePublish(courseId);
                if (coursePublish != null){
                    // 查询完成在存储到redis
                    redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish));
                    return coursePublish;
                }   
                // 数据库中没有数据 防止缓存穿透
                redisTemplate.opsForValue().set("course:" + courseId, "", 30, TimeUnit.SECONDS);
            }
        }finally {
            // 由于自己的业务可能还没有执行完，锁就已经过期了，可能会删除他人的锁
            // 防止删除他人的锁 但是不是原子操作，还是可能删除其它线程的锁
            if (redisTemplate.opsForValue().get(lockKey).toString().equals("01")){
                redisTemplate.delete(lockKey);
            }
        }
        
        
        

        return null;
    }*/

    // 用redisson解决分布式问题
    @Override
    public CoursePublish getCoursePublishCache(Long courseId) {




        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
        // 防止缓存穿透
        if ("".equals(jsonObj.toString())){
            return null;
        }
        if (jsonObj != null){
            // 缓存中有直接返回数据
            String jsonString = jsonObj.toString();
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        }
        // 分布式锁，通过setnx实现
        String lockKey = "courseLock:" + courseId;
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(30L, TimeUnit.SECONDS);
        try {
            Object jsonObj2 = redisTemplate.opsForValue().get("course:" + courseId);
            if (jsonObj2 != null){
                // 第二次检查，如果有就直接返回数据，防止重复查询数据库
                String jsonString2 = jsonObj2.toString();
                CoursePublish coursePublish2 = JSON.parseObject(jsonString2, CoursePublish.class);
                return coursePublish2;
            }
            // 从数据库查询
            CoursePublish coursePublish = getCoursePublish(courseId);
            if (coursePublish != null){
                // 查询完成在存储到redis
                redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish));
                return coursePublish;
            }
            // 数据库中没有数据 防止缓存穿透
            redisTemplate.opsForValue().set("course:" + courseId, "", 30, TimeUnit.SECONDS);
        
        }finally {
            // 由于自己的业务可能还没有执行完，锁就已经过期了，可能会删除他人的锁
            // 防止删除他人的锁
            // setNX 释放锁不是原子操作，可能会删除其它线程的锁
            // redisson看门狗机制会开启一个线程监听该键，并自动延期
            // lua脚本-保证原子操作，redisson会在释放锁时去执行该脚本
            // 释放锁
            lock.unlock();
        }




        return null;
    }

}
